package org.singledog.dogmail.common.utils;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * 序列化反序列化工具
 *
 * @author ZheMing Liu
 * @since 2022.1.18
 */
@Slf4j
public class SerialUtils {

    private static final BASE64Encoder BASE_64_ENCODER = new BASE64Encoder();

    private static final BASE64Decoder BASE_64_DECODER = new BASE64Decoder();

    /**
     * 序列化
     *
     * @param source 源对象
     * @return 序列化结果
     */
    public static String serialize(Object source) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream bys = null;
        String result = null;
        try {
            bys = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bys);
            oos.writeObject(source);
            byte[] bytes = bys.toByteArray();
            result = BASE_64_ENCODER.encode(bytes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (bys != null) {
                try {
                    bys.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return result;
    }

    public static Object unSerialize(String source) {
        ObjectInputStream ois = null;
        ByteArrayInputStream bys = null;
        Object result = null;
        try {
            byte[] bytes = BASE_64_DECODER.decodeBuffer(source);
            bys = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bys);
            result = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (bys != null) {
                try {
                    bys.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return result;
    }

}
